import { mapState, mapGetters, mapMutations, mapActions, useStore } from 'vuex';
import { computed } from 'vue';

/**
 * @param {*} namespaced 模块名
 * @param {*} getters getters方法名
 * @param {*} mutations mutations方法名
 * @param {*} actions actions方法名
 * @returns
 */
export function FactoryStore ({
	namespaced = '',
	gettersMethod = [],
	mutationsMethod = [],
	actionsMethod = []
} = {}) {
	let store = useStore();
	if (!namespaced) {
		return { store, mapState, mapGetters, mapMutations, mapActions };
	}
	// state
	let state = computed(() => store.state[namespaced].value);

	// mapGetters
	let getters = mapGetters(namespaced, gettersMethod);
	let getter = {};
	gettersMethod.forEach((key) => {
		getter[key] = computed(getters[key].bind({ $store : store }));
	});

	// mapMutations
	let mutations = mapMutations(namespaced, mutationsMethod);
	let mutation = {};
	mutationsMethod.forEach((key) => {
		mutation[key] = mutations[key].bind({
			$store : store
		});
	});

	// mapActions
	let actions = mapActions(namespaced, actionsMethod);
	let action = {};
	actionsMethod.forEach((key) => {
		action[key] = actions[key].bind({
			$store : store
		});
	});
	return {
		mapState,
		mapGetters,
		mapMutations,
		mapActions,
		store,
		state,
		getter,
		mutation,
		action
	};
}
